package com.yc.damai.damaiindex.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yc.damai.bean.Result;
import com.yc.damai.damaiindex.web.fegin.OtherAction;
import com.yc.damai.damaiindex.web.fegin.OtherActionImpl;
import com.yc.damai.damaiindex.web.fegin.UserAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/9/4
 * Email haijunzhou@hnit.edu.cn
 */
@RestController
@RefreshScope
public class IndexDo {

    @RequestMapping("index")
    String index(HttpServletRequest request){
        return "index " + request.getServerPort();
    }

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("user")
    @HystrixCommand(fallbackMethod = "hystrixUser")
    String user(){
        return restTemplate.getForObject(
                "http://damai-user/user",
                String.class);
    }

    String hystrixUser(){
        return "restTemplate 降级方法: user";
    }


    @Autowired
    UserAction userAction;

    @RequestMapping("userByFeign")
    String userByFeign(){
        return userAction.user();
    }


    @RequestMapping("hello")
    String hello(@RequestParam("name") String name){
        return userAction.hello(name);
    }

    @RequestMapping("add")
    int add(@RequestParam("a") int a, @RequestParam("b") int b){
        return userAction.add(a,b);
    }

    @RequestMapping("sub/{x}/{y}")
    String sub(@PathVariable int x, @PathVariable int y){
        return userAction.sub(x,y);
    }

    @RequestMapping("result")
    Result result( Result result){
        return userAction.result(result);
    }

    @RequestMapping("headers")
    Map<String,Object> headers(@RequestHeader("Cookie") String cookie,
                               @RequestHeader String Host){
        HashMap<String,Object> ret = new HashMap<>();
        ret.put("Cookie", cookie);
        ret.put("Host", Host);
        return ret;
    }

    /////////////////////////////////////////////////////////////////////////////

    @Autowired
    OtherAction otherAction;
    @Autowired
    @Qualifier("otherActionImpl")
    OtherActionImpl otherActionImpl;
    @RequestMapping("queryHots")
    List<?> queryHots(){
        List<?> list = otherAction.queryHots();
        otherActionImpl.setHotsCache(list);
        return list;
    }

    @Value("${myname}")
    String myname;

    @RequestMapping("myname")
    public String getMyname() {
        return myname;
    }
}
